<template>
	<div class="tikuBg">
		
		
		<u-sticky bgColor="#fff">
			<div class="banner">
				<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
			</div>
			<div class="searchBox">
				<u-search placeholder="输入关键字搜索" shape="round" v-model="searchVal"></u-search>
			</div>
		</u-sticky>
		<div class="loadBox" v-if="searchLoading">
			<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..." textSize="20"></u-loading-icon>
		</div>
		<div class="container">
			<div class="items" v-if="!searchVal">
				<div class="item" v-for="(item,index) in filterEnd" :key="index">
					<h2 class="textTlt">{{ item.time }}</h2>
					<template v-for="(t,i) in item.list">
						<h3>
							<u-parse :content="(i + 1) + '、' + t.title" :showImgMenu="false"></u-parse>
						</h3>
						<div class="d_btns">
							<div class="btn" v-if="t.answer">
								<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(t)"></u-button>
							</div>
							<div class="time">{{t.time}}</div>
						</div>
					</template>
					
				</div>
			</div>
			<div class="items" v-else>
				<template v-if="searchList.length > 0">
					<div class="item" v-for="(item,index) in searchList" :key="index">
						<h3>
							<u-parse :content="(index + 1) + '、' + item.title" :showImgMenu="false"></u-parse>
						</h3>
						<div class="d_btns">
							<div class="btn" v-if="item.answer">
								<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(item)"></u-button>
							</div>
							<div class="time">{{item.time}}</div>
						</div>
					</div>
				</template>
				<template v-else>
					<u-empty mode="search" icon="https://cdn.uviewui.com/uview/empty/search.png">
					</u-empty>

				</template>
			</div>
		</div>
		
		<u-popup :show="showDetail" @close="showDetail = false" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent">
				<h3>题目列表</h3>
				<div class="overBox">
					<ul class="tmList" v-if="detailTimu.type == '刷题模式'">
						<li v-for="(t,j) in detailTimu.list" :key="j" v-if="t.end">
							<h4>
								<u-parse :content="(j + 1) + '、' + t.title" :showImgMenu="false"></u-parse>
							</h4>
							<div class="btns" v-if="t.answer">
								<div class="btn">
									<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(t)"></u-button>
								</div>
							</div>
						</li> 
					</ul>
					<ul class="tmList" v-if="detailTimu.type == '套题模式'">
						<li v-for="(t,j) in detailTimu.list" :key="j">
							<template v-for="(tt,k) in t"  v-if="tt.end">
								<h4>
									<u-parse :content="(k + 1) + '、' + tt.title" :showImgMenu="false"></u-parse>
								</h4>
								<div class="btns" v-if="tt.answer">
									<div class="btn">
										<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(tt)"></u-button>
									</div>
								</div>
							</template>
							
						</li> 
					</ul>
				</div>
				
			</div>
		</u-popup>
		<canvas canvas-id="waterMark" class="waterMark" style="width: 100vw; height: 100vh;"></canvas>
		<image :src="waterMarkUrl" class="waterMark-bg" style="width: 100vw; height: 100vh;"></image>
	</div>
</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,
				zutiTitle:"",
				banjiDetail:"",
				selectIndex:[],
				timuDetail:"",
				leixings: [],
				lxList: [],
				lists: [],
				yjCurrent: 1,
				filterLxName: "全部类型",
				ejlxList: [],
				filterErlx: "",
				ejCurrent: 1,
				searchVal: "",
				searchLoading:true,
				addSuccess:false,
				
				selectTao: 0,
				
				allSelect:[],
				
				showDetail: false,
				pages:0,
				detailTimu: ""
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			} else {
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			}
		},
		onLoad(options) {
			this.getTimuInfo()
		},
		onShow() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'hidden',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
		},
		onHide() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'none',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
			selectBanji(){
				return this.$store.getters.selectBanji ? this.$store.getters.selectBanji : '';
			},
			allEnd(){
				let that = this
				let l = []
				l = that.allSelect.filter(item => item.end).reverse()
				return l
			},
			filterEnd(){
				let that = this
				
				let t = that.allEnd.map(item => item.zTitle)
				t = [...new Set(t)]
				let t2 = []
				t.map((item,index) =>{
					let a = item.split('-')
					t2.push(a[0] + '-' + a[1] + '-' + a[2])
				})
				t2 = [...new Set(t2)]
				let timeList = []
				t2.map((item,index) =>{
					let a = item.split('-')
					timeList.push({
						time: a[0] + '-' + a[1] + '-' + a[2],
						list:[]
					})
				})
				timeList.map((item ,index) => {
					that.allEnd.map((k,j)=>{
						if(k.zTitle.indexOf(item.time) != -1){
							timeList[index].list.push(k)
						}
					})
				})
				return timeList
			},
			searchList(){
				let that = this
				let a = []
				if(that.searchVal){
					a = that.allEnd.filter(item => item.title.indexOf(that.searchVal) != -1)
				}else{
					a = []
				}
				return a
			},
			ztReverse(){
				if(this.banjiDetail){
					let l = [...this.banjiDetail.zuti]
					return l.reverse()
				}else{
					return []
				}
				
			}
			
		},
		created() {
			let that = this;
		},
		mounted() {
			let that = this 
			
			wx.hideLoading()
			
			if(this.userphone){
				this.drawWaterMark(this.userphone);
			}else{
				this.drawWaterMark('雪恒教育-白雪面试');
			}
		},
		watch: {},
		methods: {
			...mapActions(['LogSetPhone','LogSetBanji']),
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},
			getTimuInfo(){
				let that = this
				db.collection('nbhd_tiku_banji').where({
					banji: that.selectBanji
				}).get({
					success: function(res) {
						if(res.data.length > 0){
							that.banjiDetail = res.data[0]
							that.allSelect = res.data[0].allSelect
							that.searchLoading = false
						}
					}
				})
			},
			addGl(title){
				let that = this
				if(!that.searchVal){
					return title
				}
				let sText = title
				let sKey = "<span class='searchBg'>" + that.searchVal + "</span>"
				let num = -1,
					rStr = new RegExp(that.searchVal, "g"),
					rHtml = new RegExp("\<.*?\>", "ig"), //匹配html元素
					aHtml = sText.match(rHtml); //存放html元素的数组
				sText = sText.replace(rHtml, '{~}'); //替换html标签
				sText = sText.replace(rStr, sKey); //替换key
				sText = sText.replace(/{~}/g, function() { num++;return aHtml[num];});
				return sText
			},
			
			showAnswer(item){
				let that = this
				uni.navigateTo({
					url:"./answer?tmid=" + item._id
				})
			},
		},
		components: {
			
		}
	};
</script>

<style scoped>
	@import url(./index.css);
	.taotiBox{display: flex; padding: 25rpx;}
	.taotiBox .item{padding: 10rpx; border: 1px solid #ccc; border-radius: 10rpx; margin: 0 10rpx; flex: 1;}
	.taotiBox .item.active{border-color: #f00;}
	.taotiBox .item h4{font-size: 28rpx; font-weight: bold; margin-bottom: 10rpx;}
	.taotiBox .item ul{display: flex; flex-wrap: wrap;}
	.taotiBox .item ul li{width: 10px; height: 10px; margin: 0 5rpx; border: 1px  solid #ccc;}
	.taotiBox .item ul li.cur{background-color: #f00;}
</style>